
local module = _G["BlinkHealthTextModule"]

if select(2, UnitClass("player")) ~= "DEATHKNIGHT" or not module then return end

local loaded = false
local RUNETYPE_BLOOD = 1
local RUNETYPE_UNHOLY = 2
local RUNETYPE_FROST = 3
local RUNETYPE_DEATH = 4
local iconTextures = {}
iconTextures[RUNETYPE_BLOOD] = "Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-Blood"
iconTextures[RUNETYPE_UNHOLY] = "Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-Unholy"
iconTextures[RUNETYPE_FROST] = "Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-Frost"
iconTextures[RUNETYPE_DEATH] = "Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-Death"

local L_DEATH_TRANCE = "Death Trance!"
local L_RUNE_STRIKE = "Rune Strike"
local L_HORN_OF_WINTER = "Horn of Winter"
local L_FROZEN_SOLID = "Frozen Solid"
local L_FREEZING_FOG = "Freezing Fog"
local L_KILLING_MACHINE = "Killing Machine"
local L_STRENGTH_OF_EARTH = "Strength of Earth"
local L_CRYPT_FEVER = "Crypt Fever"
local L_USE_RUNE = "Use Rune"
local L_USE_DISEASE = "Use Disease"
if GetLocale()=="koKR" then
L_DEATH_TRANCE = "죽음의 무아지경"
L_RUNE_STRIKE = "룬의 일격"
L_HORN_OF_WINTER = "겨울의 뿔피리"
L_FROZEN_SOLID = "혹한의 안개"
L_FREEZING_FOG = "단단한 얼음"
L_KILLING_MACHINE = "도살기"
L_STRENGTH_OF_EARTH = "대지력"
L_CRYPT_FEVER = "칠흑의 역병인도자"
L_USE_RUNE = "룬 표시하기"
L_USE_DISEASE = "질병시간 표시"
end

local text
local name, rank, icon, count, debufType, duration, expirationTime
local size
local auraCount
local usable, nomana
local aCount
local diseaseUpdator

local function getSize(baseSize, expirationTime, duration)
	local size = (expirationTime-GetTime()) / duration
	if size < 0.3 then
		size = baseSize * .8
	elseif size < 0.6 then
		size = baseSize * 1.0
	else
		size = baseSize * 1.2
	end
	return size / 2
end

module.config = {
	[L_KILLING_MACHINE] = {
		spellid = 51128
	},
	[L_FREEZING_FOG] = {
		spellid = 59057
	},
	[L_CRYPT_FEVER] = {
		spellid = 51160
	},
	--[] = {3, 28, false},
}

function module:init()
	self.addon.mainFrame:RegisterEvent("PLAYER_ALIVE")
	self.addon.mainFrame:RegisterEvent("LEARNED_SPELL_IN_TAB")
	self.addon.mainFrame:RegisterEvent("CHARACTER_POINTS_CHANGED")

	if self.addon.db.dk_use_rune then
		self:EnableRune()
	end

	if self.addon.db.dk_use_disease then
		self:EnableDisease()
	end

	self:update()

	if loaded==false then
		self:AddMiscConfig{
			type = "toggle",
			text = L_USE_RUNE,
			tooltip = L_USE_RUNE,
			get = function ()
				return module.addon.db.dk_use_rune
			end,
			set = function (value)
				module.addon.db.dk_use_rune = value
				if module.addon.db.dk_use_rune then
					module:EnableRune()
				else
					module:DisableRune()
				end
			end,
			disable = not module.addon.db.useModule,
		}
		self:AddMiscConfig{
			type = "toggle",
			text = L_USE_DISEASE,
			tooltip = L_USE_DISEASE,
			get = function ()
				return module.addon.db.dk_use_disease
			end,
			set = function (value)
				module.addon.db.dk_use_disease = value
				if module.addon.db.dk_use_disease then
					module:EnableDisease()
				else
					module:DisableDisease()
				end
			end,
			disable = not module.addon.db.useModule,
		}
	end
	loaded = true
end

function module:update()
	self.primary = GetSpecialization()
	for auraName, t in pairs(self.config) do
		if t.talent and t.talent > 0 then
			local name, iconTexture, tier, column, selected, available = GetTalentInfo(t.talent);
			if name and available then
				self.config[auraName].use = true
				if t.event and self.addon and self.addon.mainFrame then
					self.addon.mainFrame:RegisterEvent(t.event)
				end
			end
		else
			self.config[auraName].use = false
			if IsPlayerSpell(t.spellid) then
				self.config[auraName].use = true
				if t.event and self.addon and self.addon.mainFrame then
					self.addon.mainFrame:RegisterEvent(t.event)
				end
			end
		end
	end
end

function module:LEARNED_SPELL_IN_TAB(...)
	self:update()
end
module.CHARACTER_POINTS_CHANGED = module.LEARNED_SPELL_IN_TAB
function module:PLAYER_ALIVE(...)
	self.addon.mainFrame:UnregisterEvent("PLAYER_ALIVE")
	self:update()
end

function module:RUNE_POWER_UPDATE(...)
	self:updateRunes()
end
module.RUNE_TYPE_UPDATE = module.RUNE_POWER_UPDATE
--module.PLAYER_REGEN_DISABLED = module.RUNE_POWER_UPDATE

function module:getAuraTypeCount(unit, auraType, filter)
	if not UnitExists(unit) then return end

	local i = 1
	aCount = 0

	name, rank, icon, count, debufType, duration, expirationTime = UnitAura(unit, i, filter)
	while name do
		if debufType == auraType then
			if count > 0 then
				aCount = aCount + count
			else
				aCount = aCount + 1
			end
		end
		i = i + 1
		name, rank, icon, count, debufType, duration, expirationTime = UnitAura(unit, i, filter)
	end
	return aCount
end

function module:EnableRune()
	if not self.addon.playerFrame.runes then
		self.addon.playerFrame.runes = self.addon.playerFrame:CreateFontString(nil, "OVERLAY")
		self.addon.playerFrame.runes:SetFont(self.addon.db.font, self.addon.db.fontSizePower, self.addon.db.fontOutline)
		self.addon.playerFrame.runes:SetPoint("BOTTOM", self.addon.playerFrame.health, "TOP")
		self.addon.playerFrame.runes:SetAlpha(self.addon.db.unit.player.alpha)
		self.addon.playerFrame.runes:SetJustifyH("CENTER")
	end
	self.addon.playerFrame.runes:Show()
	self.addon.mainFrame:RegisterEvent("RUNE_POWER_UPDATE")
	self.addon.mainFrame:RegisterEvent("RUNE_TYPE_UPDATE")
end

function module:DisableRune()
	if self.addon.playerFrame.runes then
		self.addon.playerFrame.runes:Hide()
	end
	self.addon.mainFrame:UnregisterEvent("RUNE_POWER_UPDATE")
	self.addon.mainFrame:UnregisterEvent("RUNE_TYPE_UPDATE")
end

function module:EnableDisease()
	--print("EnableDisease")
	if not self.addon.playerFrame.disease then
		self.addon.playerFrame.disease = self.addon.playerFrame:CreateFontString(nil, "OVERLAY")
		self.addon.playerFrame.disease:SetFont(self.addon.db.font, self.addon.db.fontSizePower, self.addon.db.fontOutline)
		self.addon.playerFrame.disease:SetPoint("LEFT", self.addon.playerFrame.health, "RIGHT")
		self.addon.playerFrame.disease:SetAlpha(self.addon.db.unit.player.alpha)
		self.addon.playerFrame.disease:SetJustifyH("LEFT")
		self.addon.playerFrame.disease:SetTextColor(0.25, 0.25, 1.0)
	end
	self.addon.playerFrame.disease:Show()

	if not self.addon.targetFrame.disease then
		self.addon.targetFrame.disease = self.addon.targetFrame:CreateFontString(nil, "OVERLAY")
		self.addon.targetFrame.disease:SetFont(self.addon.db.font, self.addon.db.fontSizePower, self.addon.db.fontOutline)
		self.addon.targetFrame.disease:SetPoint("RIGHT", self.addon.targetFrame.health, "LEFT")
		self.addon.targetFrame.disease:SetAlpha(self.addon.db.unit.player.alpha)
		self.addon.targetFrame.disease:SetJustifyH("RIGHT")
		self.addon.targetFrame.disease:SetTextColor(0.25, 1.0, 0.25)
	end
	self.addon.targetFrame.disease:Show()

	self:RegisterUpdators(diseaseUpdator, self.addon.playerFrame.disease, self.addon.targetFrame.disease)
end

function module:DisableDisease()
	if self.addon.playerFrame.disease then
		self.addon.playerFrame.disease:Hide()
	end
	if self.addon.targetFrame.disease then
		self.addon.targetFrame.disease:Hide()
	end
	self:UnregisterUpdators(diseaseUpdator)
end

function module:getTargetText()
	text = ""
	size = self.addon.db.fontSizeHealth
	auraCount = self:getAuraTypeCount("target", "Disease", "PLAYER|HARMFUL")

	if self.config[L_CRYPT_FEVER].use then
		if auraCount == 1 then
			text  = (":|cff%02x%02x%02x%d|r"):format(255, 63, 63, auraCount)
		elseif auraCount == 2 then
			text  = (":|cff%02x%02x%02x%d|r"):format(255, 255, 63, auraCount)
		elseif auraCount > 2 then
			text  = (":|cff%02x%02x%02x%d|r"):format(63, 255, 63, auraCount)
		end
	else
		if auraCount == 1 then
			text  = (":|cff%02x%02x%02x%d|r"):format(255, 63, 63, auraCount)
		elseif auraCount > 1 then
			text  = (":|cff%02x%02x%02x%d|r"):format(63, 255, 63, auraCount)
		end
	end

	if self.config[L_KILLING_MACHINE].use then
		--name, rank, icon, count, debufType, duration, expirationTime = self:getAuraInfo("player", L_KILLING_MACHINE, "HELPFUL")
		name, rank, icon, count, debufType, duration, expirationTime = UnitAura("player", L_KILLING_MACHINE, nil, "HELPFUL")
		if name then
			size = getSize(self.addon.db.fontSizeHealth, expirationTime, duration)
			text = text .. (":|T%s:%d|t"):format(icon, size)
		end
	end

	if self.config[L_FREEZING_FOG].use then
		--name, rank, icon, count, debufType, duration, expirationTime = self:getAuraInfo("player", L_FROZEN_SOLID, "HELPFUL")
		name, rank, icon, count, debufType, duration, expirationTime = UnitAura("player", L_FROZEN_SOLID, nil, "HELPFUL")
		if name then
			size = getSize(self.addon.db.fontSizeHealth, expirationTime, duration)
			text = text .. (":|T%s:%d|t"):format(icon, size)
		end
	end

--	-- rune strike
--	usable, nomana = IsUsableSpell(L_RUNE_STRIKE)
--	_, _, icon = GetSpellInfo(L_RUNE_STRIKE)
--	if usable then
--		size = self.addon.db.fontSizeHealth * 1.2 / 2
--		text = text .. (":|T%s:%d|t"):format(icon, size)
--	end

--	-- horn of winter
--	if UnitLevel("player")>=65 and not UnitAura("player", L_HORN_OF_WINTER, nil, "HELPFUL") and not UnitAura("player", L_STRENGTH_OF_EARTH, nil, "HELPFUL") then
--		size = self.addon.db.fontSizeHealth * 1.2 / 2
--		--text = text .. (":|T%s:%d:%d:0:0|t"):format("Interface\\Icons\\INV_Misc_Horn_02", size, size)
--		text = text .. (":|T%s:%d|t"):format("Interface\\Icons\\INV_Misc_Horn_02", size)
--	end

	return text
end

local runes = {0,0,0,0}
function module:updateRunes()
	local text = ""
	local runeReady, runeType
	runes = {0,0,0,0}
	for k, i in pairs {1, 2, 5, 6, 3, 4} do -- 머야;;; 순서대로 해도되는건데...
		_, _, runeReady = GetRuneCooldown(i)
		runeType = GetRuneType(i)
		if runeType then
			if runeReady then
				runes[runeType] = runes[runeType] + 1
			end
		end
	end
	text = ("|cff%02x%02x%02x%d|r|cff%02x%02x%02x%d|r|cff%02x%02x%02x%d|r|cff%02x%02x%02x%d|r"):format(
		255, 63, 63, runes[RUNETYPE_BLOOD],
		63, 63, 255, runes[RUNETYPE_FROST],
		63, 255, 63, runes[RUNETYPE_UNHOLY],
		255, 63, 255, runes[RUNETYPE_DEATH])
	self.addon.playerFrame.runes:SetText(text)
end

function diseaseUpdator(unit, f1, f2)
	if not UnitExists("target") then
		f1:SetText("")
		f2:SetText("")
		return
	end

	local now, leftTime = GetTime(), 0
	--local name, _, _, _, _, duration, expirationTime = module:getAuraInfo("target", "", "PLAYER|HARMFUL")
	local name, _, _, _, _, duration, expirationTime = UnitAura("target", "서리 열병", nil, "PLAYER|HARMFUL")
	if name then
		leftTime = expirationTime - now
		if leftTime > 0 then
			f1:SetText( ("%d"):format(leftTime) )
		else
			f1:SetText("")
		end
	end

	name, _, _, _, _, duration, expirationTime = UnitAura("target", "피의 역병", nil, "PLAYER|HARMFUL")
	if name then
		leftTime = expirationTime - now
		if leftTime > 0 then
			f2:SetText( ("%d"):format(leftTime) )
		else
			f2:SetText("")
		end
	end
end
